<?php
/**
 * Created by PhpStorm.
 * User: liuweiping
 * Date: 16/8/3
 * Time: 15:20
 */

function showHomepage($aid_index = 0, $gid_index = 0)
{
    $path = "";

    $CI =& get_instance();
    $session_user = $CI->session->session_user;
    if (!empty($session_user)) {
        if (is_numeric($aid_index)) {
            $app_list = $session_user['app_list'];
            if (!empty($app_list)) {
                $app = array();
                for ($i = 0; $i < count($app_list); $i++) {
                    if ($i == $aid_index) {
                        $app = $app_list[$i];
                        break;
                    }
                }
                if (empty($app)) {
                    $app = $app_list[0];
                }
                $session_user['oper_aid'] = $app['id'];
                $path .= '/' . $app['mgr_web_uri'] . '/';
                $gid = 0;
                $group_name = "";
                if (is_numeric($gid_index)) {
                    $group_list = $app['group_list'];
                    if (!empty($group_list)) {
                        $group = array();
                        for ($j = 0; $j < count($group_list); $j++) {
                            if ($j == $gid_index) {
                                $group = $group_list[$j];
                                break;
                            }
                        }
                        if (empty($group)) {
                            $group = $group_list[0];
                        }
                        $gid = $group['id'];
                        $group_name = $group['name'];
                    }
                } else {
                    $path = '/';
                }
                $session_user['oper_gid'] = $gid;
                $session_user['group_name'] = $group_name;
            } else {
                $CI->session->unset_userdata('session_user');
                jumpPage("您当前的账号尚未分配应用,请联系管理员!");
                return;
            }
        } else {
            $CI->session->unset_userdata('session_user');
            jumpPage("非法操作,请重新登录!");
            return;
        }
    } else {
        $path = '/user/logout';
    }

    $CI->session->set_userdata(array('session_user' => $session_user));
    if (!checkGroup()) {
        $CI->session->unset_userdata('session_user');
        jumpPage('当前应用已被禁用, 请重新登录');
    } else {
        redirect($path);
    }
}

function checkGroup()
{
    $result = api_request('rosefinch.web.group.check');
    log_message('error', " CHECKGROUP_RESULT-> " . $result);
    $json = json_decode($result, true);
    $code = $json['code'];
    if ($code == 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 从Session中判断用户是否已登录,是否已经修改初始密码.
 * @return int 登录状态: 0 未登录; -1 已登录但为默认密码; 1 已登录已修改密码.
 */
function isLogin()
{
    $CI =& get_instance();
    $session_user = $CI->session->session_user;
    if (empty($session_user) || empty($session_user['id'])) {
        return 0;
    }
    return $session_user['is_modify_pwd'] == 1 ? 1 : -1;
}

function checkLogin()
{
    $CI =& get_instance();
//    error_log('error', 'is_login: '. isLogin());
    switch (isLogin()) {
        case 1:
            showHomepage();
            break;
        case -1:
            $data = array(
                'error_msg' => '检测到您使用初始密码进行登录, 为保护您的账号安全,避免他人盗用, 请立即修改登录密码'
            );
            $CI->load->view('resetPassword', $data);
            break;
        case 0:
        default:
            jumpPage();
            break;
    }
}

function jumpPage($msg = null, $viewPage = 'login')
{
    $CI =& get_instance();
    $campus_id = 0;
    $campus_name = '';
    $pc_login_img = '';
    $code = 0;
    $session = $CI->session;
    if (!$session->has_userdata('campus')
        || !array_key_exists('name', $session->get_userdata('campus'))
        || !array_key_exists('id', $session->get_userdata('campus'))
    ) {
        $host = $_SERVER['HTTP_HOST'];
        $length = strpos($host, ':');
        $domain = $length > 0 ? substr($host, 0, $length) : $host;
        $params = array(
            'domain' => $domain
        );

        $result = api_request('rosefinch.web.campus.get_by_domain', $params);
        log_message('error', 'GET_BY_DOMAIN_REQUEST: ' . $result);
        $json = json_decode($result, true);
        $code = $json['code'];
        $campus = $json['body'];
        $session->set_userdata(array('campus' => $campus));
        $campus_id = $campus['id'];
        $campus_name = $campus['name'];
        $pc_login_img = $campus['pc_login_img'];

//        echo '<pre>';
//        print_r('domain: ' . $domain);
//        echo '</pre>';
    }
    log_message('error', 'goLogin: ' . json_encode($session));


    $data = array(
        'campus' => array(
            'id' => $campus_id,
            'name' => $campus_name,
            'pc_login_img' => $pc_login_img
        ),
        'code' => $code
    );
    log_message('error', json_encode($data));
    if (!empty($msg)) {
        $data['error_msg'] = $msg;
    }

    $CI->load->view($viewPage, $data);
}


/**
 * 创建验证码
 * @return array 验证码对象 array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename);
 * @deprecated 废弃
 */
function get_captcha()
{
    $CI =& get_instance();
    $code = $this->captcha->getCaptcha();
    $CI->session->set_userdata(array('word' => $code));
    $this->captcha->showImg();
}
// 原 验证码 获取方法
//function get_captcha()
//{
//    $vals = array(
//        'word' => rand(1000, 9999),
//        'img_path' => './captcha/',
//        'img_url' => base_url() . 'captcha/',
//        'font_path' => './system/fonts/texb.ttf',
//        'img_width' => '100',
//        'img_height' => 50,
//        'font_size' => 16,
//        'img_id' => 'captcha_img',
//        'expiration' => 600
//    );
//    $CI =& get_instance();
//    $CI->session->set_userdata(array('word' => $vals['word']));
//    $cap = create_captcha($vals);
//    return $cap;
//}